<template lang="pug">
div
  FixedScroll
    div(slot="fixed")
      PageHeader(pageTitle="电池扫描")
        div.active(slot="right" @click="save") 确认

      ScanSearch(
          placeholder="序列号"
          :initSearchValue="searchValue"
          @search="search"
          @scan="search"
          )

      div.info(v-if="info")
        KvPair(v-if="info.PartNo" k="物料号" :v="info.PartNo")
        KvPair(v-if="info.RequiredQty" k="需求数量" :v="info.RequiredQty")
        KvPair(v-if="info.ActualQty" k="实际数量" :v="info.ActualQty")

    ColoredTable.table(
        slot="scroll"
        :headList="headList"
        :body="body"
        :statusMap="statusMap"
        :isLoading="isLoading"
        @delete-row="deleteRow"
        )

</template>

<script>
/* 
  query
    PartNo
    RequiredQty
    ActualQty
    ReceiveNo
    ReceiveDetailId
    PullSupplierNum
 */
import api from "$api"
import util from "$util"
import { mapState } from "vuex"

export default {
  data() {
    let query = this.$route.query
    let info = {
      PartNo: query.PartNo,
      RequiredQty: query.RequiredQty,
      ActualQty: query.ActualQty,
    }

    return {
      searchValue: "",
      info,

      loading: {
        search: false,
      },

      isLoading: false,
      headList: [
        { field: "delete-row", title: "", checked: true },
        { field: "BarcodeData", title: "序列号", checked: true },
        { field: "Qty", title: "数量", checked: true },
        { field: "PartNo", title: "物料号", checked: true },
        { field: "PartName", title: "物料名称", checked: true },
      ],
      body: {
        list: [],
      },
      statusMap: {},
      codeMap: {},
    }
  },
  computed: {
    ...mapState({
      barcodeDetail: state => state.battery.barcodeDetail,
    }),
  },
  methods: {
    async search(value) {
      if (this.loading.search) {
        return
      }
      if (value === "") {
        return
      }

      if (this.codeMap[value]) {
        return
      }

      this.loading.search = true
      try {
        let query = this.$route.query
        let data = await api.BatteryCheckBarcode({
          ReceiveNo: query.ReceiveNo,
          PullSupplierNum: query.PullSupplierNum,
          BarcodeData: value,
          PartNo: query.PartNo,
        })
        data.BarcodeData = data.Dcbbm
        data.Qty = 1
        data["delete-row"] = true

        let status = ""
        if (data.PartNo === this.info.PartNo) {
          if (this.info.ActualQty === this.info.RequiredQty) {
            util.Alert("电池扫描数量已足够", "错误")
            return
          }
          this.info.ActualQty++
          // 添加一行电池数据
          this.$store.commit("battery/addBarcode", {
            id: this.$route.query.ReceiveDetailId,
            data,
          })
          status = util.STATUS_OK
        } else {
          util.Alert(`${value}不在此仓库`, "错误")
          return
          status = util.STATUS_ERROR
        }

        this.body.list.push(data)
        this.statusMap[value] = status
        this.codeMap[value] = true

      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.search = false
      }
    },

    save() {
      util.Toast("保存成功")
    },

    // 初始化已有的电池列表
    async init() {
      try {
        let query = this.$route.query
        let data = await api.BatteryInfo({
          ReceiveDetailId: query.ReceiveDetailId,
          ReceiveNo: query.ReceiveNo,
        })
        let scanMap = this.barcodeDetail[query.ReceiveDetailId]
        if (scanMap) {
          for (let k in scanMap) {
            data.push(scanMap[k])
          }
        }

        for (let [i, item] of data.entries()) {
          data[i].Qty = 1
          this.statusMap[item.BarcodeData] = util.STATUS_OK
          this.codeMap[data[i].BarcodeData] = true
        }
        this.body.list = data
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
      }
    },

    // 删除一行
    deleteRow(barcode) {
      this.codeMap[barcode] = false

      let bodyIndex = -1
      for (let [i, item] of this.body.list.entries()) {
        if (item.BarcodeData === barcode) {
          bodyIndex = i
          break
        }
      }
      if (bodyIndex >= 0) {
        this.body.list.splice(bodyIndex, 1)
      }

      let id = this.$route.query.ReceiveDetailId
      let old = this.barcodeDetail[id]
      if (old && (barcode in old)) {
        this.info.ActualQty--
      }
      this.$store.commit("battery/removeBarcode", {
        id,
        BarcodeData: barcode,
      })

    },

    registerScanner() {
      util.registerScanner((data) => {
        this.searchValue = data
        this.search(data)
      })
    },
  },

  created() {
    this.registerScanner()
    this.init()
  },
}
</script>

<style lang="stylus" scoped>

.active:active
  active-color()

.info
  border: 1px solid grey200

.table
  scan-table()

</style>
